package com.github.binarywang.demo.wx.mp.handler;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.demo.wx.mp.builder.TextBuilder;
import com.github.binarywang.demo.wx.mp.service.WeixinService;
import com.x.base.vo.BaseResponse;
import com.x.centra.customer.api.wechat.interfaces.ICustWechatSV;
import com.x.centra.customer.api.wechat.params.WechatParam;
import com.x.sdk.component.mds.IMessageSender;
import com.x.sdk.component.mds.MDSClientFactory;
import com.x.sdk.dubbo.util.DubboConsumerFactory;
import com.x.sdk.mds.vo.BusinessMessage;
import com.x.sdk.util.DateUtil;
import com.x.wx.constant.MdsConstant;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Binary Wang
 */
@Component
public class MsgHandler extends AbstractHandler {

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) {

		WeixinService weixinService = (WeixinService) wxMpService;
		// 回复内容
		String content = "";
		if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
			if (StringUtils.startsWith(wxMessage.getContent(), "绑定#")) {
				String[] contentArray = wxMessage.getContent().split("#");
				if (contentArray.length < 2) {
					content = "格式不正确，请回复如下内容绑定手机号码\n绑定#138XXXX8888";
				} else {
					String phoneNumber = contentArray[1];
					String regExp = "^1\\d{10}$";
					Pattern p = Pattern.compile(regExp);
					Matcher m = p.matcher(phoneNumber);
					if (m.matches()) {
						// 获取微信用户基本信息
						WxMpUser userWxInfo = null;
						try {
							userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
						} catch (WxErrorException e) {
							this.logger.error("获取微信用户信息失败", e);
						}
						if (userWxInfo != null) {
							WechatParam wechatParam = new WechatParam();
							wechatParam.setAccountName(userWxInfo.getNickname());
							wechatParam.setAccountOpenId(userWxInfo.getOpenId());
							wechatParam.setAccountType("0");
							wechatParam.setImgUrl(userWxInfo.getHeadImgUrl());
							wechatParam.setPhone(phoneNumber);
							wechatParam.setTenantId("pubgo");
							if (this.logger.isInfoEnabled()) {
								this.logger.info("用户激活参数: {}", JSON.toJSONString(wechatParam));
							}
							// 用户激活
							BaseResponse baseResponse = DubboConsumerFactory.getService(ICustWechatSV.class)
									.custActive(wechatParam);
							if (this.logger.isInfoEnabled()) {
								this.logger.info("用户激活返回: {}", JSON.toJSONString(baseResponse));
							}
							if (baseResponse.getResponseHeader().isSuccess()) {
								content = "恭喜,绑定成功";
							} else {
								content = "绑定失败，请稍后再试";
							}
						}
					} else {
						content = "手机号码格式不正确";
					}
				}
			} else {
				// send msg
				IMessageSender iMessageSender = MDSClientFactory.getSenderClient(MdsConstant.NameSpace.RECEIVE_MESSAGE);
				BusinessMessage businessMessage = new BusinessMessage();
				businessMessage.setBusiType(wxMessage.getMsgType());
				businessMessage.setCreateTime(DateUtil.getSysDate());
				businessMessage.setMsgID(String.valueOf(wxMessage.getMsgId()));
				businessMessage.setData(JSON.toJSONString(wxMessage));
				iMessageSender.send(businessMessage, new Random(1000L).nextLong());
			}
		}
		// 当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
		// if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
		// && weixinService.hasKefuOnline()) {
		// return WxMpXmlOutMessage
		// .TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
		// .toUser(wxMessage.getFromUser()).build();
		// }

		if (StringUtils.isBlank(content)) {
			return null;
		}
		return new TextBuilder().build(content, wxMessage, weixinService);

	}
}
